from django.contrib.contenttypes.models import ContentType
from rest_framework import viewsets, serializers, permissions
from .models import Comment, Notification, Message
from .serializers import *
from ctbloge.apps.cms.models import Article, Like
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework import status
from django.shortcuts import get_object_or_404
from rest_framework.pagination import PageNumberPagination
from ctbloge.apps.accounts.models import UserProfile
from django.db.models import Count, Q
from django.db.models import Case, When, BooleanField

# 自定义分页器
class CommentPagination(PageNumberPagination):
    page_size = 15
    page_size_query_param = 'page_size'
    max_page_size = 100


class CommentViewSet(viewsets.ModelViewSet):
    queryset = Comment.objects.all().order_by('-created_date')
    serializer_class = CommentSerializer
    permission_classes = [IsAuthenticated]
    pagination_class = CommentPagination

    def get_serializer_class(self):
        if self.action == 'create':
            return CommentCreateSerializer
        return CommentSerializer

    def perform_create(self, serializer):
        content = self.request.data.get('content', None)
        if not content:
            raise serializers.ValidationError('评论内容不能为空')

        # 获取当前文章
        if 'article' in self.request.data:
            article_id = self.request.data['article']
            article = Article.objects.get(id=article_id)
        else:
            article = None

        # 处理父评论逻辑
        parent_comment = self.request.data.get('parent', None)
        if parent_comment:
            parent = Comment.objects.get(id=parent_comment)
            parent_article = parent.article

            # 获取父评论的层级深度
            current_level = 0
            current_parent = parent
            while current_parent.parent:
                current_level += 1
                current_parent = current_parent.parent

            # 如果父评论已经是二级评论
            if current_level >= 1:
                parent = parent.parent
                current_level = parent.parent.level if parent.parent else 0

            new_level = current_level + 1
            comment = serializer.save(
                author=self.request.user,
                article=parent_article,
                parent=parent,
                content=content,
                level=new_level
            )
            # 给父评论作者发送通知
            if parent.author != self.request.user:  # 防止评论自己
                Notification.objects.create(
                    receiver=parent.author,
                    verb='reply',
                    sender=self.request.user,
                    content='{} 回复了你的评论《{}》'.format(self.request.user.nickname, parent.content[:20])
                )
        else:
            comment = serializer.save(
                author=self.request.user,
                article=article,
                content=content,
                level=0
            )
        # 评论后给作者发送通知

        if article.author != self.request.user:
            Notification.objects.create(
                receiver=article.author,
                verb='comment',
                sender=self.request.user,
                content='{} 评论了你的文章《{}》'.format(self.request.user.nickname, article.title)
            )

        # 更新返回的数据，添加 `user` 信息
        serializer.instance = comment

    def get_comment_level(self, comment):
        level = 0
        while comment.parent:
            level += 1
            comment = comment.parent
        return level

    # 获取所有的一级评论,增加分页,权限设置为所有人可访问,不用登录
    @action(methods=['get'], detail=False, permission_classes=[AllowAny])
    def get_root_comments(self, request):
        queryset = Comment.objects.filter(parent=None)

        # 分页处理（核心逻辑）
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        # 处理未分页的情况（兜底逻辑）
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    # 获取所有的二级评论
    @action(methods=['get'], detail=False)
    def get_second_comments(self, request):
        comments = Comment.objects.filter(parent__parent=None)
        serializer = CommentSerializer(comments, many=True)
        return Response(serializer.data)

    # 新增评论点赞功能
    @action(methods=['post'], detail=True)
    def like(self, request, pk=None):
        comment = get_object_or_404(Comment, pk=pk)
        content_type = ContentType.objects.get_for_model(comment)

        # 检查用户是否已经点赞了该评论
        like, created = Like.objects.get_or_create(
            user=request.user,
            content_type=content_type,
            object_id=comment.id
        )
        if not created:
            like.delete()
            comment.likes_count -= 1
            comment.save()
            return Response({'message': '取消点赞成功', 'like_count': comment.likes_count, 'isliked': False})
        else:
            comment.likes_count += 1
            comment.save()
            return Response({'message': '点赞成功', 'like_count': comment.likes_count, 'isliked': True})

    # 查询用户是否已经点赞了该评论
    @action(methods=['get'], detail=True)
    def is_liked(self, request, pk=None):
        comment = get_object_or_404(Comment, pk=pk)
        content_type = ContentType.objects.get_for_model(comment)
        like_count = Like.objects.filter(
            user=request.user,
            content_type=content_type,
            object_id=comment.id
        )
        if like_count.exists():
            return Response({'message': '已点赞', 'isliked': True, 'likes_count': comment.likes_count})
        else:
            return Response({'message': '未点赞', 'isliked': False, 'likes_count': comment.likes_count})

    # 获取最新评论列表
    @action(methods=['get'], detail=False)
    def get_latest_comments(self, request):
        comments = Comment.objects.filter(parent=None).order_by('-created_date')[:10]
        serializer = CommentSerializer(comments, many=True)
        return Response(serializer.data)


# 待完成：创建一个管理视图，允许管理员查看未审核的评论，并提供审核通过和删除的选项。



class NotificationViewSet(viewsets.ModelViewSet):
    """
    通知接口支持：
    - 分页获取通知
    - 获取未读数量
    - 批量标记已读
    """
    pagination_class = CommentPagination
    serializer_class = NotificationSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        """基于接收者过滤，按时间倒序排列"""
        """增加系统通知过滤条件"""


        queryset = Notification.objects.filter(
            receiver=self.request.user,
            is_receiver_deleted=False
        )
        queryset = queryset.annotate(
            is_unread=Case(
                When(status='unread', then=True),
                default=False,
                output_field=BooleanField()
            )
        )
        verb_param = self.request.query_params.get('verb')
        if verb_param:
            # 将逗号分隔的字符串转为列表
            verbs = verb_param.split(',')
            # 使用正确的 __in 查询语法
            queryset = queryset.filter(verb__in=verbs)

        if self.request.query_params.get('system_level'):
            queryset = queryset.filter(system_level=self.request.query_params.get('system_level'))

        return queryset.order_by('-is_unread', '-timestamp')

    @action(detail=False, methods=['get'])
    def unread_count(self, request):
        """获取当前用户的未读通知数量"""
        count = self.get_queryset().filter(status='unread').count()
        return Response({'count': count})
    @action(detail=False, methods=['get'])
    def category_counts(self, request):
        """获取各分类的未读数量"""
        counts = {
            'all': {'total': self.get_queryset().count(),
                    'unread_count': self.get_queryset().filter(status='unread').count()},
            'system': {'total': self.get_queryset().filter(verb='system').count(),
                       'unread_count': self.get_queryset().filter(verb='system', status='unread').count()},
            'message': {'total': self.get_queryset().filter(verb='message').count(),
                        'unread_count': self.get_queryset().filter(verb='message', status='unread').count()},
            'interaction':
                {'total': self.get_queryset().filter(
                    verb__in=['comment', 'reply', 'like', 'follow', 'collect', 'mention'],
                ).count(),
                 'unread_count': self.get_queryset().filter(
                     verb__in=['comment', 'reply', 'like', 'follow', 'collect', 'mention'],
                     status='unread'
                 ).count()},
        }
        return Response(counts)

    @action(detail=False, methods=['patch'])
    def mark_all_as_read(self, request):
        """标记所有通知为已读"""
        updated = self.get_queryset().filter(status='unread').update(status='read')
        return Response({'marked_count': updated})

    @action(detail=True, methods=['patch'])
    def mark_as_read(self, request, pk=None):
        """标记单条通知为已读"""
        instance = self.get_object()
        if instance.status != 'read':
            instance.status = 'read'
            instance.save()
            return Response({'status': 'read'})
        return Response({'status': 'already read'}, status=status.HTTP_400_BAD_REQUEST)

    def perform_destroy(self, instance):
        """软删除：标记接收者删除字段"""
        instance.is_receiver_deleted = True
        instance.save()

    @action(detail=False, methods=['post'], permission_classes=[permissions.IsAdminUser])
    def send_system_notification(self, request):
        """管理员发送系统通知"""
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save(
            verb='system',
            sender=None,  # 系统通知无具体发送者
            is_broadcast=request.data.get('is_broadcast', False)
        )
        return Response(serializer.data, status=status.HTTP_201_CREATED)


# 留言视图集
class MessageViewSet(viewsets.ModelViewSet):
    serializer_class = MessageSerializer
    permission_classes = [permissions.AllowAny]

    def get_queryset(self):
        return Message.objects.all().order_by('-created_date')

    # 新增留言
    @action(methods=['post'], detail=False, permission_classes=[IsAuthenticated])
    def create_message(self, request):
        content = request.data.get('content', None)
        if not content:
            return Response({'message': '留言内容不能为空'}, status=status.HTTP_400_BAD_REQUEST)
        message = Message.objects.create(
            sender=self.request.user,
            content=content,
        )
        # 给管理员发送通知
        Notification.objects.create(
            receiver=UserProfile.objects.get(is_superuser=True),
            verb='message',
            sender=self.request.user,
            content='{} 给你留言'.format(self.request.user.nickname)
        )
        data = MessageSerializer(message).data
        return Response({'message': '留言成功', 'data': data})
    # 获取用户的留言列表
    @action(methods=['get'], detail=False, permission_classes=[AllowAny ])
    def get_danmu_list(self, request):
        messages = Message.objects.all().order_by('-created_date')
        serializer = DanmuSerializer(messages, many=True)
        return Response(serializer.data)